package com.zzg.srb.core.utils;

import com.zzg.srb.base.utils.JwtUtils;
import com.zzg.srb.common.exception.Assert;
import com.zzg.srb.common.result.ResponseEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author zhengzg
 * @Date 2022/8/11 17:30
 * @Version 1.0
 */
@Slf4j
@Component
public class CurrentLoginUserUtils {

    @Value("${authorization.login.user}")
    private String loginUser;

    private static String userToken;

    /**
     * PostConstruct 注释用于在依赖关系注入完成之后需要执行的方法上，以执行任何初始化
     */
    @PostConstruct
    public void init(){
        CurrentLoginUserUtils.userToken = loginUser;
    }

    /**
     * 获取用户Id
     * @return UserInfo
     */
    public static Long getLoginUser(){

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        //出现请求错误，抛出异常
        Assert.notNull(attributes, ResponseEnum.ERROR);
        HttpServletRequest request = attributes.getRequest();
        String userInfo = request.getHeader(userToken);
        return JwtUtils.getUserId(userInfo);
    }

    public static Map<String,Object> getUserInfo() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        //出现请求错误，抛出异常
        Assert.notNull(attributes, ResponseEnum.ERROR);
        HttpServletRequest request = attributes.getRequest();
        String userInfo = request.getHeader(userToken);
        Long userId = JwtUtils.getUserId(userInfo);
        String userName = JwtUtils.getUserName(userInfo);
        Map<String, Object> map = new HashMap<>();
        map.put("userId",userId);
        map.put("userName",userName);
        return map;
    }
}
